<script>
export default {
  name: "PetSearch",
  data() {
    return {
      fileList:[
        {
          name:'food.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        }
      ],
      searchKeyword: '',
      dialogFormVisible: false,
      form: {
        petName: '',
        loseType: '',
        content: '',
        location: '',
        loseTime: '',
        phoneNum: '',
        imageFile: null,
        ownerNo:'',
        status:'',
      },
      rules: {
        petName: [{ required: true, message: '请输入宠物名字', trigger: 'blur' }],
        location: [{ required: true, message: '请输入丢失位置', trigger: 'blur' }],
        phoneNum: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern:/^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' },
        ],
      },
      pets: [],
    }
  },
  computed: {
    user() {
      return this.$store.state.user // 从Vuex获取用户信息
    }
  },
  mounted() {
    this.loadPets()
  },
  methods:{
    Finish() {
      this.$router.replace("/")
    },
    // 加载宠物数据
    async loadPets() {
      try {
        const res = await this.$axios.post(this.$httpUrl + '/search/listPageS', {
          pageNum: 1,
          pageSize: 10,
          param: {
            keywords: this.searchKeyword.trim()
          }
        })
        if (res.data.code === 200) {
          this.pets = res.data.data
              .filter(item => item.status !== 2)
              .map(item => ({
            ...item,
            imageUrl: `${this.$httpUrl}/search/image/${item.id}?t=${Date.now()}`,
            loseTime: this.formatTime(item.loseTime)
          }))
        }
      } catch (error) {
        this.$message.error('数据加载失败')
      }
    },

    // 时间格式化
    formatTime(time) {
      return new Date(time).toLocaleString('zh-CN')
    },

    // 处理搜索
    handleSearch() {
      this.loadPets()
    },
    // 清除搜索框内容并重新加载数据
    clearSearch() {
      this.searchKeyword = ''; // 清空搜索框
      this.loadPets(); // 重新加载数据
    },
    // 打开发布表单
    handlePublish() {
      if (!this.user) {
        this.$message.error('请先登录！')
        return
      }
      this.dialogFormVisible = true
      this.form = { // 重置表单
        petName: '',
        loseType: '',
        location: '',
        imageFile: '',
        content: '',
        loseTime:'',
        phoneNum:'',
        ownerNo:this.user.no,
      };
      this.fileList = [];
    },

    formatDateTime(date) {
      if (!date) return '';
      const d = new Date(date);
      const pad = num => num.toString().padStart(2, '0');
      return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ` +
          `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
    },
    // 提交表单
    async submitForm() {
      const formData = new FormData();
      formData.append('petName', this.form.petName);
      formData.append('loseType', this.form.loseType);
      formData.append('content', this.form.content);
      formData.append('location', this.form.location);
      formData.append('loseTime', this.formatDateTime(this.form.loseTime));
      formData.append('phoneNum', this.form.phoneNum);
      formData.append('ownerNo', this.user.no);
      formData.append('status', 0);
      if (this.form.imageFile) {
        formData.append('imageFile', this.form.imageFile);
      }

      try {
        const res = await this.$axios.post(
            '/search/save',
            formData,
            {
              headers: {
                'Content-Type': 'multipart/form-data; charset=utf-8' // 显式指定字符集
              }
            }
        );
        if (res.data.code === 200) {
          this.$message.success('发布成功')
          this.dialogFormVisible = false
          this.loadPets()
        }
      } catch (error) {
        this.$message.error('提交失败')
      }
    },

    // 标记已找到
    async handleFound(id) {
      try {
        const res = await this.$axios.post(`/search/markFound/${id}`);
        if (res.data.code === 200) {
          this.$message.success(res.data.msg || '已经提交申请到后台');
          this.loadPets();
        }
      } catch (error) {
        this.$message.error(error.response?.data?.msg || '操作失败');
      }
    }
  },
}
</script>

<template>
  <div class="pet-search-container">
    <!-- 标题区域 -->
    <header class="header">
      <el-link :underline="false"
               class="back-link"
               @click.native="Finish"
               icon="el-icon-back"
      >
      </el-link>
      <h1 class="title">ReunitePets</h1>
    </header>
    <div class="divider"></div>
    <!-- 搜索和按钮区域 -->
    <div class="search-bar">
      <div class="container">
        <div class="input-group">
          <input
              type="text"
              class="form-control"
              v-model="searchKeyword"
              placeholder="输入宠物名称或位置..."
              @keyup.enter="handleSearch"
          >
          <!-- 清除按钮 -->
          <div class="input-group-append">
            <button
                class="btn btn-clear"
                @click="clearSearch"
                v-if="searchKeyword"
            >
              <i class="el-icon-close"></i>
            </button>
            <button class="btn btn-publish" @click="handleSearch">
              <i class="fas fa-search"></i> 搜索
            </button>
          </div>
          <div class="input-group-append">
            <button class="btn btn-publish"
                    @click="handlePublish">
              <i class="fas fa-plus"></i> 发布信息
            </button>
          </div>
        </div>
      </div>
    </div>
    <!-- 宠物卡片网格 -->
    <div class="container pet-grid">
      <div class="row">
        <div
            class="col-12 col-sm-6 col-md-4 col-lg-3 mb-4"
            v-for="(pet, index) in pets"
            :key="index"
        >
          <div class="pet-card">
            <div class="card-image">
              <img :src="pet.imageUrl" alt="宠物照片" class="img-fluid">
            </div>
            <div class="card-content">
              <h3 class="pet-name">{{ pet.petName }}</h3>
              <div class="pet-info">
                <p><strong>品种：</strong>{{ pet.loseType }}</p>
                <p><strong>特征：</strong>{{ pet.content }}</p>
                <p><strong>位置：</strong>{{ pet.location }}</p>
                <p><strong>丢失时间：</strong>{{ pet.loseTime }}</p>
              </div>
              <div class="contact-info">
                <span class="contact-label">联系方式：</span>
                {{ pet.phoneNum }}
              </div>
              <div v-if="user && user.no === pet.ownerNo" class="found-btn">
                <el-popconfirm
                    confirm-button-text='确定'
                    confirm-button-type="warning"
                    cancel-button-text='点错了'
                    icon="el-icon-info"
                    icon-color="red"
                    title="点击后将不再找寻，确认吗？"
                    @confirm="handleFound(pet.id)"
                    style="margin-left: 5px">
                  <el-button
                      slot="reference"
                      type="danger"
                      size="small"
                  >
                    已 找 到
                  </el-button>
                </el-popconfirm>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 发布对话框 -->
    <el-dialog title="发布寻宠信息" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules">
        <el-form-item label="宠物照片" prop="imageFile">
          <el-upload
              action="/dummy-upload-url"
              :auto-upload="false"
              :on-change="file => form.imageFile = file.raw"
          >
            <el-button size="small">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="宠物名字" prop="petName">
          <el-input v-model="form.petName"></el-input>
        </el-form-item>
        <el-form-item label="品种类型">
          <el-input v-model="form.loseType"></el-input>
        </el-form-item>
        <el-form-item label="特征描述">
          <el-input type="textarea" v-model="form.content"></el-input>
        </el-form-item>
        <el-form-item label="丢失位置" prop="location">
          <el-input v-model="form.location"></el-input>
        </el-form-item>
        <el-form-item label="丢失时间">
          <el-date-picker
              v-model="form.loseTime"
              type="datetime"
              placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="联系方式" prop="phoneNum">
          <el-input v-model="form.phoneNum"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.pet-search-container {
  min-height: 100vh;
  background-color: #FFF3E0;
}

.header {
  background-color: #FFF8E1;
  padding: 20px 0;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.back-link {
  position: absolute;
  left: 10px;
  z-index: 1;
  /deep/ .el-icon-back {
    margin-right: 5px;
  }
}

.title {
  color: #FF8A65;
  font-size: 1.5rem;
  font-weight: 600;
  letter-spacing: 1px;
  text-align: left;
  margin-left: 70px;
}

.search-bar {
  padding: 30px 0;
  background-color: #FFF8E1;
}
.btn-clear {
  background-color: transparent;
  border: none;
  color: #666;
  cursor: pointer;
  padding: 0 10px;
}
.btn-clear:hover {
  color: #ff4d4d; /* 鼠标悬停时变为红色 */
}

.btn-publish {
  background-color: #42b983;
  color: white;
  border-radius: 0 4px 4px 0;
  padding: 10px 20px;
  margin-right: 5px;
}

.btn-publish:hover {
  background-color: #35a371;
}

.divider {
  border-bottom: 1px solid #BDBDBD;
  margin: 0 auto;
  width: 95%;
}

.pet-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.3s ease;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.pet-card:hover {
  transform: translateY(-5px);
}

.card-image img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-bottom: 1px solid #eee;
}

.card-content {
  padding: 15px;
}

.pet-name {
  color: #2c3e50;
  font-size: 1.25rem;
  margin-bottom: 10px;
}

.pet-info {
  color: #666;
  font-size: 0.9rem;
  line-height: 1.6;
}

.pet-info p {
  margin-bottom: 5px;
}

.contact-info {
  margin-top: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  font-size: 0.85rem;
  color: #42b983;
}

.contact-label {
  color: #666;
  font-weight: 500;
}
/* 已找到按钮样式 */
.found-btn {
  margin-top: 15px;
  text-align: center;
}

/* 时间选择器宽度调整 */
.el-date-editor {
  width: 100%;
}

/* 图片上传样式 */
.el-upload {
  display: block;
}
</style>